package ca.ulaval.ift.gloo.SimSolution.presentation;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;

public class Grid {
	
	//largeur et hauteur maximun de la grille
	public static final int MAX_WIDTH = 2000;
	public static final int MAX_HEIGHT = 2000;
	
	
	//intervalle entre deux lignes
	public static final int GRID_GAP = 3;
	
	
	
	//largeur et hauteur de la grille
	private int width;
	private int height;
	
	//zoom appliqué à la grille
	private int zoom;
	
	//image qui constitue la grille
	private BufferedImage buffer;
	
	
	public Grid(int width, int height, int zoom){
		this.setWidth(width);
		this.setHeight(height);
		this.setZoom(zoom);
		
	}

	public void paintGrid(Graphics g){
		update();
		if(buffer!=null)
			g.drawImage(buffer, 0, 0, null);

	}
	public void update(){
		//intilisation de la grille
		buffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
		
		//On récupére un objet graphic pour déssiner dans l'image
		Graphics2D g2 = buffer.createGraphics();
		
		//couleur de fonds blanc
		g2.setColor(Color.WHITE);
		g2.fillRect(0, 0, getWidth(), getHeight());
		
		//couleur des traits
		g2.setColor(Color.LIGHT_GRAY);
		
		//Style de trait
		BasicStroke stroke = new BasicStroke(0, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER);
		g2.setStroke(stroke);
		
		//espacement entre les lignes en tenant compte du zoom
		int gap = getGridGap();
		
		//On dessine les lignes verticales
		for(int i=gap-1; i<width; i+=gap)
            g2.draw(new Line2D.Double(i, 0, i, height));
		
		//On dessine les lignes horizontales
		for(int j=gap-1; j<height; j+=gap)
            g2.draw(new Line2D.Double(0, j, width, j));
		
	}

	public Point getGridPoint(Point pt){
		
	
		int gap = getGridGap();
        float x = pt.x;
        float y = pt.y;
        int divRes;
        float modulo;
		
        //calcul de l'abscisse pour correspondre à la grille
        divRes = (int)(x/gap);
        modulo = x % gap;
        
        if(modulo < (gap/2)) 
        	pt.x = divRes * gap;
        else
        	pt.x = (divRes+1) * gap;
        
        
        //calcul de l'ordonnée pour correspondre à la grille
        divRes = (int)(y/gap);
        modulo = y % gap;
        
        if(modulo < (gap/2)) 
        	pt.y = divRes * gap;
        else
        	pt.y = (divRes+1) * gap;
		
		return pt;
	}
			
	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width > MAX_WIDTH ? MAX_WIDTH : width;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height > MAX_HEIGHT ? MAX_HEIGHT : height;
	}

	public int getZoom() {
		return zoom;
	}

	public void setZoom(int zoom) {
		this.zoom = zoom;
	}
	
	public int getGridGap() {
		return GRID_GAP * getZoom();
	}
	
	

}
